//
//  BaseTabBarController.swift
//  CandyDate
//
//  Created by zolobdz on 2018/1/26.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import AVFoundation
import CoreLocation

class BaseTabBarController: UITabBarController {

    lazy var homepageViewController = HomepageViewController()
    lazy var meViewController = MeViewController()
    
//    lazy var homepageNavigationController = HomepageNavgationController(rootViewController: HomepageBaseViewController())
//    lazy var messageNavigationController = MessageNavigationController(rootViewController: MessageListViewController())
//    lazy var centerNavigationController = BaseNavigationController(rootViewController: UIViewController())
//    lazy var contactsNavigationController = ContactsNavigationController(rootViewController: ContactsViewController())
//    lazy var meNavigationController = MeNavigationController(rootViewController: MeViewController())
    lazy var messageRedPointView: UIView = {
        let width = DeviceInfo.screenWidth.doubleValue()/5.0
        let x = width*3.0/2.0+10.0
        let view = UIView(frame: CGRect(x: x, y: 4, width: 8.0, height: 8.0))
        view.backgroundColor = UIColor.red
        view.layer.cornerRadius = 4.0
        view.layer.masksToBounds = true
        view.isHidden = true
        return view
    }()
    
//    lazy var contactRedPointView: UIView = {
//        let width = DeviceInfo.screenWidth.doubleValue()/5.0
//        let x = width*7.0/2.0+10.0
//        let view = UIView(frame: CGRect(x: x, y: 4, width: 8.0, height: 8.0))
//        view.backgroundColor = UIColor.red
//        view.layer.cornerRadius = 4.0
//        view.layer.masksToBounds = true
//        view.isHidden = true
//        return view
//    }()
    var addFriendClosure :CDSimpleClosure? = nil
    
    
    
    lazy var isEnteredBackground = true // 是否进入了后台（因为仅仅判断appbecomeActive不够，系统的alert也会调用appbecomeActive导致弹出密码框）
    
    var lastPlayDate = Date(timeIntervalSince1970: 0)
    lazy var soundID: SystemSoundID = 0
    lazy var mustUpdate = false
    lazy var updatingContent = ""
    lazy var appstoreURLString = ""
    
    // 拍照相关
    lazy var pickerViewController = UIImagePickerController()
    lazy var qiniuToken = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tabBar.isTranslucent = false
        
        let homeNav = BaseNavigationController(rootViewController: homepageViewController)
        homeNav.tabBarItem.title = "首页"
        homeNav.tabBarItem.image = R.image.home_normal()
        homeNav.tabBarItem.selectedImage = R.image.home_select()
        //        homepageNavigationController.tabBarItem.image = UIImage(resource: R.image.tabbar_homepage_normal)!.withRenderingMode(.alwaysOriginal)
        //        homepageNavigationController.tabBarItem.selectedImage = UIImage(resource: R.image.tabbar_homepage_selected)!.withRenderingMode(.alwaysOriginal)
        
        let meNav = BaseNavigationController(rootViewController: meViewController)
        meNav.tabBarItem.title = "我的"
        meNav.tabBarItem.image = R.image.me_normal()
        meNav.tabBarItem.selectedImage = R.image.me_select()
        //        homepageNavigationController.tabBarItem.image = UIImage(resource: R.image.tabbar_homepage_normal)!.withRenderingMode(.alwaysOriginal)
        //        homepageNavigationController.tabBarItem.selectedImage = UIImage(resource: R.image.tabbar_homepage_selected)!.withRenderingMode(.alwaysOriginal)
        
        viewControllers = [homeNav,
                           meNav]
        
        
        tabBar.tintColor = CDColor.themePink
        
    }
    
    //MARK: Public
    
    
    
    //MARK: Action
    
    
    //MARK: Private
    
    func judgeLocationService() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: {
                CDLocationService.shared.requestLocationServiceWhenInUse()
            })
        case .denied,.restricted:
            if CDLocationService.shared.checkIsDeviceLocationEnable() || !CDLocationService.shared.checkIsOpenAppLocationAuthority()
            {
                let alert = UIAlertController(title: "定位服务未开启", message: "请在手机设置中开启定位服务\n来使用更多功能~", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "设置", style: .default, handler: { (action) in
                    let url = URL(string: UIApplicationOpenSettingsURLString)
                    if url != nil && UIApplication.shared.canOpenURL(url!)
                    {
                        self.navigationController?.popToRootViewController(animated: true)
                        UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                    }
                })
                let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                alert.addAction(cancel)
                alert.addAction(okAction)
                present(alert, animated: true, completion: nil)
            }
            
            if !CDLocationService.shared.checkIsDeviceLocationEnable()
            {
                let alert = UIAlertController(title: "定位服务未开启", message: "请在手机设置中开启定位服务\n来使用更多功能~", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "好的", style: .default, handler: { (action) in
                })
                alert.addAction(okAction)
                present(alert, animated: true, completion: nil)
            }
            
        default:
            break
        }
    }
    
    // 用户登录后需要获取qiniutoken的方法 读取本地qntoken，如果没有或者是过期了自动获取，自动获取弹hud。6小时获取一次
    func getUserQiniuToken() {
        if let userID = MyselfSingleton.shared.userInfo?.userID
        {
//            if let modelJSON = UserDefaults.standard.object(forKey: CDUserDefaultKey.userQiNiuToken + userID) as? Dictionary<String,String>,!modelJSON.isEmpty
//            {
//                if let tokenModel = QiNiuToken(JSON: modelJSON)
//                {
//                    if !tokenModel.token.isEmpty
//                    {
//                        let formatter = DateFormatter()
//                        formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
//                        let expireDate = formatter.date(from: tokenModel.expireDate) ?? Date() // 过期时间
//                        let nowDate = Date(timeIntervalSinceNow: 0) // 现在时间
//                        if expireDate.compare(nowDate) == .orderedDescending
//                        {
//                            qiniuToken = tokenModel.token
//                            return
//                        }
//                        CDUtility.log("qiniu token过期啦")
//                    }
//                }
//            }
            requestQiniuToken()
        }
    }
    
    // 获取登陆后的qiniuToken
    private func requestQiniuToken() {
        
//        guard let userID = MyselfSingleton.shared.userInfo?.userID,userID.count > 0 else {
//            return
//        }
        
//        CDNetWorkService.requestDataWithTarget(
//            target: CDRequestAPI.getQiNiuToken(ShowHudKey: true, userID: userID),
//            type: QiNiuToken.self,
//            successClosure: { [weak self] (model,code,msg) in
//                if let strongSelf = self{
//                    if code == 10
//                    {
//                        if var m = model as? QiNiuToken
//                        {
//                            strongSelf.qiniuToken = m.token
//                            //设置过期时间
//                            let nowDate = Date(timeIntervalSinceNow: 60*60*6)//6小时后过期
//                            let formatter = DateFormatter()
//                            formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
//                            let dateString = formatter.string(from: nowDate)
//                            m.expireDate = dateString
//                            CDUtility.log("设置update qiniu token time : \(dateString)")
//
//                            let json = m.toJSON()
//                            UserDefaults.standard.set(json, forKey: CDUserDefaultKey.userQiNiuToken+userID)
//                            strongSelf.makeToast("请重新点击")
//                        }
//                    }
//                    else{
//                        strongSelf.makeToast(msg)
//                    }
//
//                }
//        }) { [weak self] (msg) in
//            if let strongSelf = self{
//                strongSelf.makeToast(msg+"获取失败")
//            }
//        }
    }

}


